<?php

namespace app\admin\service;
use app\admin\traits\ServiceTrait;
use app\admin\util\JwtUtil;

class UserService
{
    //仓库
    public static $repository = 'app\admin\repository\UserRepository';

    use ServiceTrait;

    public static function login($username, $password, $ip)
    {
        //账户信息查询
        $user = self::$repository::getInfoByName($username,['user_id','create_time','password']);
        if (empty($user)) {
            throw new \app\MyException(11104);
        }
        //账户密码验证
        if ($user['password'] !== encrypt_pass($password, strtotime($user['create_time']))) {
            throw new \app\MyException(11105);
        }
        //账户状态检测
        if ($user['disabled']) {
            throw new \app\MyException(11106);
        }
        //数据处理和令牌获取
        $time = time();
        //登录事件
        event('UserLogin', [$user, $time, $ip]);
        //令牌
        $payload['user_id'] = $user['user_id'];
        $payload['login_time'] = $time;
        $token = think_encrypt(JwtUtil::encode($payload));
        //返回数据
        return array(
            'token' => $token
        );
    }

    /**
     * 根据user_id获取role_id
     * @param $id
     * @return mixed
     */
    public static function getRolesByIDs($id){
        return self::$repository::getRolesByID($id);
    }
}